from helpers import updateInfo
from helpers import Fetching
from helpers import Visualization
import urllib
import os
from google.appengine.ext.webapp import template
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db

class MainPage(webapp.RequestHandler):
    """ Stock profile page class """
    def get(self):
        user=users.get_current_user()
        # Make sure user is logged in, if not redirect to login page
        if not user:
            self.redirect(users.create_login_url(self.request.uri))
            return
    
        # Check for valid key
        if not self.request.get('TKey'):
            self.response.out.write("Please insert a valid stock ID")
            return
        
        # Load user info from database
        # If user is using app for first time (=his info in not in TrendUsers table)
        # then initialize his info
        current_user=updateInfo.getCurrentUser(user)
    
        # Build top 10 (all times) earners table
        try:
            currentTrend = db.get(db.Key(self.request.get('TKey')))
        except:
            self.response.out.write("Please insert a valid stock ID")
            return
        
        # Check for valid key
        if currentTrend==None or (not type(currentTrend) is updateInfo.StocksData and not type(currentTrend) is updateInfo.ETFData):
            self.response.out.write("Please insert a valid stock ID")
            return
     
        i=0
        numberofRows=5
        
        # Get transcation info of stock for the current user
        q_1=currentTrend.stocks_set
        ETFcountHolders=q_1.count()
        q_2=q_1.filter('buyer =', user)
        if q_2.count()==0:
            if type(currentTrend) is updateInfo.StocksData:
                perforText='<a href="/buy?q=%s">Buy this stock</a>' % currentTrend.stockname.capitalize()
            else:
                perforText='<a href="/buy">You do not own this ETF. Buy it now!</a>'
            # Buying date (-1 since user did not buy this stock/ETF)
            buyingDate=-1
            buyingPrice=-1
        else:
            q_2=q_2.fetch(1)[0]
            perforPrct, perforColor, perforChangeSign = updateInfo.getPerInfo(q_2.userPrecentChange)
            if q_2.userPrecentChange<1:
                perforChangeSign="-"
            elif q_2.userPrecentChange>1:
                perforChangeSign="+"
            else:
                perforChangeSign=""
                
            perforText='<span style="color:%s">%s %%%.2f</span>' % (perforColor, perforChangeSign, perforPrct)
            # Buying date (-1 since user did not buy this stock/ETF)
            buyingDate=q_2.buydate.strftime("%Y,%m,%d")
            buyingPrice=q_2.buyValue
            
        fmonthPrintPercentage=""
        MonthPrintPercentage=""
        fmonthFontColor=""
        MonthFontColor=""
        fmonthChangeSign=""
        MonthChangeSign=""
        # If StockData type
        if type(currentTrend) is updateInfo.StocksData:
            showStock=1
            stockname=currentTrend.stockname.capitalize()
            stockHolders=currentTrend.stockcounter
            searchQuery=currentTrend.stockname
            topRegionsList=currentTrend.topRegions
            relatedSearchesList=currentTrend.relatedSearches
            table1Text="Top Regions"
            # Get stock icon
            showIcon=1
            # If there isn't an icon already, get it
            if not currentTrend.stockIcon: 
                # Get stock icon, if failed, do not show icon on page
                if Fetching.imageForStock(currentTrend)==-1:
                    showIcon=0            
    
            #monthPrintPercentage, monthFontColor, monthChangeSign = updateInfo.getPerInfo(currentTrend.MonthChange)
            #tMonthPrintPercentage, tMonthFontColor, tMonthChangeSign = updateInfo.getPerInfo(currentTrend.ThreeMonthChange)
            
            graph_text=Visualization.buildStockGraph(currentTrend, 1, buyingDate, buyingPrice)
            
            if currentTrend.FifteenDaysChange:
                FifteenDaysChange=currentTrend.FifteenDaysChange
                fmonthPrintPercentage, fmonthFontColor, fmonthChangeSign = updateInfo.getPerInfo(FifteenDaysChange)
                if FifteenDaysChange<1:
                    fmonthChangeSign="-"
                elif FifteenDaysChange>1:
                    fmonthChangeSign="+"
                else:
                    fmonthChangeSign=""
                if currentTrend.MonthChange:
                    MonthChange=currentTrend.MonthChange
                    MonthPrintPercentage, MonthFontColor, MonthChangeSign = updateInfo.getPerInfo(MonthChange)
                    if MonthChange<1:
                        MonthChangeSign="-"
                    elif MonthChange>1:
                        MonthChangeSign="+"
                    else:
                        MonthChangeSign=""
            
            
        # We already know this will be of ETFData
        else:
            showStock=0
            topRegionsList=[]
            relatedSearchesList=[]
            stockname=currentTrend.categoryref.category.capitalize()
            stockHolders=ETFcountHolders
            searchQuery=""
            table1Text="Stocks In ETF"
            showIcon=0
                
            #building Seasonality graph for ETF
            graph_text=Visualization.buildStockGraph(currentTrend,2, buyingDate, buyingPrice)
            
            for etfTrend in currentTrend.stocklist:
                etfTrend=db.get(etfTrend)
                searchQuery+="%s," % etfTrend.stockname
                if etfTrend.topRegions and len(etfTrend.topRegions)>0:
                    topRegionsList.append(etfTrend.stockname)
                if etfTrend.relatedSearches and len(etfTrend.relatedSearches)>0:
                    relatedSearchesList.append(etfTrend.relatedSearches[0])
        
        regions_trend_Text="\ndata.addRows(%d);\n" % min (len(topRegionsList), numberofRows)
        topRegion="None"
        for p in topRegionsList:
            if i==0: 
                topRegion=topRegionsList[0]
            p=p.replace("'","\\'")
            regions_trend_Text+="data.setCell(%d, 0, '%s', '%s');\n" % (i,p,p)
            i=i+1
            if i==numberofRows:
                break;
    
        i=0
        related_trend_Text="\ndata2.addRows(%d);\n" % min(len(relatedSearchesList), numberofRows)
        for p in relatedSearchesList:
            p=p.replace("'","\\'")
            try:
                related_trend_Text+="data2.setCell(%d, 0, '%s', '<a href=\"/buy?q=%s\" style=\"color:#000000\">%s</a>');\n" % (i,p,urllib.quote(p),p)
            except:
                1
            i=i+1
            if i==numberofRows:
                break;
                
        printPercentage, fontColor, changeSign= updateInfo.getPerInfo(currentTrend.precentChange)
        
        if type(currentTrend) is updateInfo.ETFData:
            if currentTrend.updatedate==None:
                lastUpdate="(No Data Yet)"
            else:
                lastUpdate=currentTrend.updatedate.strftime("%b, %d")
        else:
            if currentTrend.yahooupdatedate==None and currentTrend.updatedate==None:
                lastUpdate="(No Data Yet)"
            elif (currentTrend.yahooupdatedate!=None and currentTrend.updatedate==None) or currentTrend.yahooupdatedate>currentTrend.updatedate:
                lastUpdate=currentTrend.yahooupdatedate.strftime("%b, %d %H:%M")
            else:
                lastUpdate=currentTrend.updatedate.strftime("%b, %d")
            
        inCategory=currentTrend.categoryref.category
    
        if currentTrend.precentChange<1:
            changeSign="-"
        elif currentTrend.precentChange>1:
            changeSign="+"
        else:
            changeSign=""
            
        if currentTrend.isProfile:
            showData=1
        else:
            showData=0
        
        
        template_values = {
            'graph_text': graph_text,
            'current_user_totalamount': current_user.totalamount,
            'current_user_bankamount': current_user.bankamount,
            'current_user_investamount': current_user.totalamount-current_user.bankamount,
            'logusername' : user.nickname().capitalize(),
            'loginurl' : users.create_logout_url("/"),
            'logintext' : 'Sign Out',
            'showData': showData,
            'categoryName' : '<span style="color:#3366CC;">%s</span>' %(stockname) + ' <span style="color:#1F1F1F;">|</span> Profile Page',
            'searchQuery' : searchQuery,
            'table1Text' : table1Text,
            'ImageUrl' :  "/getimage/%s" % self.request.get('TKey'),
            'changePercentage' : "%.2f" % printPercentage,
            'stockHolders' : stockHolders,
            'stockname' : stockname,
            'fontColor': fontColor,
            'changeSign':changeSign,
            'lastUpdate': lastUpdate,
            'topRegion' : topRegion,
            'inCategory' : inCategory,
            'showIcon' : showIcon,
            'fMonthPrintPercentage': fmonthPrintPercentage,
            'MonthPrintPercentage': MonthPrintPercentage,
            'fMonthFontColor': fmonthFontColor,
            'MonthFontColor': MonthFontColor,
            'fMonthChangeSign': fmonthChangeSign,
            'MonthChangeSign': MonthChangeSign,
            'perforText': perforText,
            'showStock' : showStock,
            'regions_trend_Text' : regions_trend_Text,
            'related_trend_Text': related_trend_Text,
            'setHead' : 1,
            'maincontent' : 'account_main.html',
            'headContent' : 'tprofile_head.html',
            'account_main_content' : 'tprofile_main.html'
            
        }
        path = os.path.join(os.path.dirname(__file__), updateInfo.controllersIndexPath)
        self.response.out.write(template.render(path, template_values))


application = webapp.WSGIApplication(
                                     [('/trendProfile', MainPage)],
                                     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
